package com.jz.yanshe.ui.fragment;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jz.jd.rest.business.RestProxy;
import com.jz.jd.rest.response.BannerResponse;
import com.jz.jd.rest.response.Goods;
import com.jz.jd.rest.response.HotGoodsResponse;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import com.jz.yanshe.base.BaseFragment;
import com.jz.yanshe.eventbus.ChooseHot;
import com.jz.yanshe.ui.widget.CheckBoxText;
import com.jz.yanshe.ui.widget.CustomPopWindow;
import com.jz.yanshe.util.ImageLoaderHelper;
import com.jz.yanshe.ui.GoodsDetailActivity;
import jz.com.feierman.R;

/**
 * Created by Administrator on 2018/2/26.
 */

public class HotFragment extends BaseFragment {

    @BindView(R.id.swipe_target)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.banner)
    Banner banner;
    int page = 1;
    int goodsCategoryId;
    int sortByType;
    int descOrAsc;
    @BindView(R.id.tv_sale_num)
    TextView tv_sale_num;

    @BindView(R.id.img_sale_num)
    ImageView img_sale_num;


    @BindView(R.id.tv_price)
    TextView tv_price;

    @BindView(R.id.img_price)
    ImageView img_price;

    @BindView(R.id.tv_new)
    TextView tv_new;

    @BindView(R.id.img_new)
    ImageView img_new;

    @BindView(R.id.btn_type)
    ImageView btn_type;

    MyAdapter myAdapter = new MyAdapter();
    List<Goods> list = new ArrayList<>();
    List<String> list_banner = new ArrayList<>();
    private CustomPopWindow mListPopWindow;
    ArrayList<CheckBoxText> listType = new ArrayList<>();
    String type;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_hot;
    }

    public static HotFragment newInstance(String type) {
        Bundle args = new Bundle();
        args.putString("TYPE", type);
        HotFragment fragment = new HotFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        recyclerView.setAdapter(myAdapter);
        recyclerView.setNestedScrollingEnabled(false);
        GridLayoutManager gridLayoutManager;
        if(type.equals("4")){
            gridLayoutManager = new GridLayoutManager(getActivity(), 1);
        }else{
            gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        }
        gridLayoutManager.setSmoothScrollbarEnabled(true);
        gridLayoutManager.setAutoMeasureEnabled(true);
        recyclerView.setLayoutManager(gridLayoutManager);

        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 10;
                outRect.right = 10;
            }
        });
        refreshLayout.setRefreshFooter(new BallPulseFooter(getActivity()).setSpinnerStyle(SpinnerStyle.Scale));
        refreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                getHotGoods(page, 10, descOrAsc, sortByType, goodsCategoryId);

            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                page++;
                getHotGoods(page, 10, descOrAsc, sortByType, goodsCategoryId);

            }
        });
//        swipeToLoadLayout.setOnRefreshListener(this);
//        swipeToLoadLayout.setOnLoadMoreListener(this);
    }

    @Override
    protected void initData() {
        type = getArguments().getString("TYPE");
        getBanner();
        getHotGoods(1, 10, descOrAsc, sortByType, goodsCategoryId);
    }


//    @Override
//    public void onLoadMore() {
//        page++;
//        getHotGoods(page, 10,descOrAsc,sortByType,goodsCategoryId);
//    }
//
//    @Override
//    public void onRefresh() {
//        page = 1;
//        getHotGoods(1,10,descOrAsc,sortByType,goodsCategoryId);
//    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {


        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_hot, parent, false));
            return holder;
        }


        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putString("goodsid", list.get(position).goods_id);
                    startActivity(GoodsDetailActivity.class, bundle);
                }
            });
            ImageLoaderHelper.getInstance().GlideImageLoader(getActivity(), list.get(position).goods_icon, holder.img_goods, R.mipmap.img_hot_default);
            holder.tv_price.setText("¥ " + list.get(position).goods_price);
            holder.tv_name.setText(list.get(position).goods_name);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {
            TextView tv_name, tv_price;
            ImageView img_goods;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_price = itemView.findViewById(R.id.tv_price);
                img_goods = itemView.findViewById(R.id.img_goods);
            }
        }
    }


    private void getHotGoods(final int page, int pageSize, int descOrAsc, int sortByType, int goodsCategoryId) {
        RestProxy.getInstance().getHotGoods(page, pageSize, descOrAsc, sortByType, goodsCategoryId, type,new Observer<HotGoodsResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(HotGoodsResponse hotGoodsResponse) {
                if (page == 1) {
                    list.clear();
                }
                list.addAll(hotGoodsResponse.listM);
                myAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                refreshLayout.finishLoadMore(false/*,false*/);//传入false表示加载失败
                refreshLayout.finishRefresh(false/*,false*/);//传入false表示加载失败
//                swipeToLoadLayout.setRefreshing(false);
//                swipeToLoadLayout.setLoadingMore(false);
            }

            @Override
            public void onComplete() {
                refreshLayout.finishLoadMore(true/*,false*/);//传入false表示加载失败
                refreshLayout.finishRefresh(true/*,false*/);//传入false表示加载失败

//                swipeToLoadLayout.setRefreshing(false);
//                swipeToLoadLayout.setLoadingMore(false);
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ChooseHot event) {
        this.descOrAsc = event.descOrAsc;
        this.goodsCategoryId = event.goodsCategoryId;
        this.sortByType = event.sortByType;
        page = 1;
        getHotGoods(1, 10, descOrAsc, sortByType, goodsCategoryId);
    }


    private void getBanner() {
        RestProxy.getInstance().getBanner(new Observer<BannerResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BannerResponse bannerResponse) {
                list_banner.clear();
                for (BannerResponse.Banner banner : bannerResponse.list) {
                    list_banner.add(banner.banner_url);
                }
                banner.setImages(list_banner).setBannerStyle(BannerConfig.CIRCLE_INDICATOR)
                        .setBannerAnimation(Transformer.Tablet).setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {
                        ImageLoaderHelper.getInstance().GlideImageLoader(context, (String) path, imageView);
                    }
                }).start();
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    @OnClick(R.id.btn_type)
    void btn_type(){
        showPopListView();
    }


    @OnClick(R.id.btn_sale_num)
    void btn_sale_num() {
        page = 1;
        if (sortByType != 1) {
            descOrAsc = 1;
        }
        if (sortByType == 1) {
            if (descOrAsc == 1) {
                descOrAsc = 2;
                getHotGoods(page, 10, descOrAsc, sortByType, goodsCategoryId);
                img_sale_num.setImageResource(R.mipmap.icon_vip_more_up_red);
            } else {
                descOrAsc = 1;
                getHotGoods(page, 10, descOrAsc, sortByType, goodsCategoryId);
                img_sale_num.setImageResource(R.mipmap.icon_vip_more_down_red);
            }
            tv_sale_num.setTextColor(getResources().getColor(R.color.commonRed));
            tv_price.setTextColor(getResources().getColor(R.color.commonBlack));
            tv_new.setTextColor(getResources().getColor(R.color.commonBlack));
            img_price.setImageResource(R.mipmap.icon_vip_more_down_grey);
            img_new.setImageResource(R.mipmap.icon_vip_more_down_grey);
        } else {
            descOrAsc = 1;
            sortByType = 1;
            getHotGoods(page, 10, descOrAsc, sortByType, goodsCategoryId);
            img_sale_num.setImageResource(R.mipmap.icon_vip_more_down_red);
            tv_sale_num.setTextColor(getResources().getColor(R.color.commonRed));
            tv_price.setTextColor(getResources().getColor(R.color.commonBlack));
            tv_new.setTextColor(getResources().getColor(R.color.commonBlack));
            img_price.setImageResource(R.mipmap.icon_vip_more_down_grey);
            img_new.setImageResource(R.mipmap.icon_vip_more_down_grey);
        }
    }

    @OnClick(R.id.btn_price)
    void btn_price() {
        page = 1;
        if (sortByType != 2) {
            descOrAsc = 1;
        }
        if (sortByType == 2) {
            if (descOrAsc == 1) {
                descOrAsc = 2;
                getHotGoods(page, 10, descOrAsc, sortByType, goodsCategoryId);
                img_price.setImageResource(R.mipmap.icon_vip_more_up_red);
            } else {
                descOrAsc = 1;
                getHotGoods(page, 10, descOrAsc, sortByType, goodsCategoryId);
                img_price.setImageResource(R.mipmap.icon_vip_more_down_red);
            }
            tv_price.setTextColor(getResources().getColor(R.color.commonRed));
            tv_sale_num.setTextColor(getResources().getColor(R.color.commonBlack));
            tv_new.setTextColor(getResources().getColor(R.color.commonBlack));
            img_sale_num.setImageResource(R.mipmap.icon_vip_more_down_grey);
            img_new.setImageResource(R.mipmap.icon_vip_more_down_grey);
        } else {
            descOrAsc = 1;
            sortByType = 2;
            getHotGoods(page, 10, descOrAsc, sortByType, goodsCategoryId);
            img_price.setImageResource(R.mipmap.icon_vip_more_down_red);
            tv_price.setTextColor(getResources().getColor(R.color.commonRed));
            tv_sale_num.setTextColor(getResources().getColor(R.color.commonBlack));
            tv_new.setTextColor(getResources().getColor(R.color.commonBlack));
            img_sale_num.setImageResource(R.mipmap.icon_vip_more_down_grey);
            img_new.setImageResource(R.mipmap.icon_vip_more_down_grey);
        }
    }

    @OnClick(R.id.btn_new)
    void btn_new() {
        page = 1;
        if (sortByType != 3) {
            descOrAsc = 1;
        }
        if (sortByType == 3) {
            if (descOrAsc == 1) {
                descOrAsc = 2;
                getHotGoods(page, 10, descOrAsc, sortByType, goodsCategoryId);
                img_new.setImageResource(R.mipmap.icon_vip_more_up_red);
            } else {
                descOrAsc = 1;
                getHotGoods(page, 10, descOrAsc, sortByType, goodsCategoryId);
                img_new.setImageResource(R.mipmap.icon_vip_more_down_red);
            }
            tv_new.setTextColor(getResources().getColor(R.color.commonRed));
            tv_price.setTextColor(getResources().getColor(R.color.commonBlack));
            tv_sale_num.setTextColor(getResources().getColor(R.color.commonBlack));
            img_price.setImageResource(R.mipmap.icon_vip_more_down_grey);
            img_sale_num.setImageResource(R.mipmap.icon_vip_more_down_grey);
        } else {
            descOrAsc = 1;
            sortByType = 3;
            getHotGoods(page, 10, descOrAsc, sortByType, goodsCategoryId);
            img_new.setImageResource(R.mipmap.icon_vip_more_down_red);
            tv_new.setTextColor(getResources().getColor(R.color.commonRed));
            tv_price.setTextColor(getResources().getColor(R.color.commonBlack));
            tv_sale_num.setTextColor(getResources().getColor(R.color.commonBlack));
            img_price.setImageResource(R.mipmap.icon_vip_more_down_grey);
            img_sale_num.setImageResource(R.mipmap.icon_vip_more_down_grey);
        }
    }


    private void showPopListView() {
        listType.clear();
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_mall, null);
//        contentView.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                int descOrAsc = 0;
//                int sortByType = 0;
//                int goodsCategoryId = 0;
//                for (CheckBoxText cbt : listType) {
//                    if (cbt.isCheck) {
//                        goodsCategoryId = cbt.goodsCategoryId;
//                    }
//                }
//
//                EventBus.getDefault().post(new ChooseHot(descOrAsc, sortByType, goodsCategoryId));
//
//
//                mListPopWindow.dissmiss();
////                swipeToLoadLayout.setRefreshing(true);
////                getMissionList();
//                //               tv_platform.setText();
//            }
//        });

        CheckBoxText checkBoxText1 = contentView.findViewById(R.id.textView32);
        CheckBoxText checkBoxText2 = contentView.findViewById(R.id.textView34);
        CheckBoxText checkBoxText3 = contentView.findViewById(R.id.textView35);
        checkBoxText1.goodsCategoryId = 43;
        checkBoxText2.goodsCategoryId = 44;
        checkBoxText3.goodsCategoryId = 45;

        listType.add(checkBoxText1);
        listType.add(checkBoxText2);
        listType.add(checkBoxText3);
        CheckBoxText.OnGroup onGroup1 = new CheckBoxText.OnGroup() {
            @Override
            public void onGroup() {
                for (CheckBoxText cbt : listType) {
                    cbt.isCheck = false;
                    cbt.clear();
                }
            }

            @Override
            public void startDate() {
                int descOrAsc = 0;
                int sortByType = 0;
                int goodsCategoryId = 0;
                for (CheckBoxText cbt : listType) {
                    if (cbt.isCheck) {
                        goodsCategoryId = cbt.goodsCategoryId;
                    }
                }
                getHotGoods(page, 10, descOrAsc, sortByType, goodsCategoryId);
//                EventBus.getDefault().post(new ChooseHot(descOrAsc, sortByType, goodsCategoryId));
                mListPopWindow.dissmiss();
            }
        };
        checkBoxText1.onGroup = onGroup1;
        checkBoxText2.onGroup = onGroup1;
        checkBoxText3.onGroup = onGroup1;


        //处理popWindow 显示内容
        //创建并显示popWindow
        mListPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                .setView(contentView)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) // 显示大小
                .create()
                .showAsDropDown(btn_type, 0, 0);
    }
}
